<template>
  <div class="left-nav">
    <el-switch class="btn-on-off" active-color="#409eff" inactive-color="#666" v-model="isCollapse"></el-switch>
    <el-menu
      :default-active="$route.path"
      background-color="#333"
      text-color="#fff"
      active-text-color="#409eff"
      unique-opened
      router
      :collapse="!isCollapse"
    >
      <el-submenu :index=" (key + 1) + '' " v-for="(menu,key) in menus" :key="key">
        <template slot="title">
          <!-- 一级菜单图标 -->
          <i :class="menu.icon"></i>
          <!-- 一级菜单标题 -->
          <span slot="title">{{ menu.title }}</span>
        </template>
          <!-- 二级菜单 授权按钮列表-->
        <template v-for="(v,i) in menu.submenus">
          <template v-if="v.submenus.length">
            <el-submenu :index="i" :key="i">
              <template slot="title">{{ v.subtitle }}</template>
              <el-menu-item
              :index="a.path"
              v-for="(a,j) in v.submenus"
              :key="j"
              @click="getRole(a.index)">{{ a.subtitle }}</el-menu-item>
            </el-submenu>
          </template>
            <template v-else>
              <el-menu-item-group :key="i">
                <el-menu-item
                  :index="v.path"
                  :key="i"
                  @click="getRole(v.index)"
                >{{ v.subtitle }}</el-menu-item>
              </el-menu-item-group>
            </template>
        </template>
      </el-submenu>
    </el-menu>
  </div>
</template>

<script>
export default {
  name: 'menuList',
  data () {
    return {
      // 收起/展开状态
      isCollapse: true,
      // 授权菜单数据
      menus: [],
      // 所有菜单数据
      // treelist: [],
      // 授权按钮
      btnlist: {}
    };
  },
  created () {
    // 获取所有菜单数据
    this.getMenusList();
  },
  methods: {
    // 获取登录用户授权菜单
    getAllMenus () {
      let _this = this;
      let params = {
        userId: _this.$store.state.userinfo.userId
      };
      // 请求登录用户授权菜单
      _this.$http.get('/api/getMenus', params).then(res => {
        let { code, datas } = res;
        if (code === 0) {
          // 存入授权目录信息Vuex loaclstorage
          _this.$store.commit('setMenus', datas);
          // 执行菜单匹配
          _this.getMenus(datas);
        }
      }).catch(err => {
        if (err === undefined) {
          _this.$message({
            message: '服务器响应异常！',
            type: 'error'
          });
          return false;
        }
        // 路由跳转
        _this.$router.push('/home');
      });
    },

    // 获取所有菜单数据
    getMenusList () {
      let _this = this;
      _this.$http.post('api/findAllMenuNoPage').then(res => {
        let { code, datas } = res;
        if (code === 0) {
          // _this.treelist = datas;
          sessionStorage.setItem('allMenus', JSON.stringify(datas));
          _this.getAllMenus();
        }
      }).catch(err => {
        if (err === undefined) {
          this.$message({
            message: '服务器响应异常！',
            type: 'error'
          });
          return false;
        }
      });
    },

    // 收起/展开
    collapseChage () {
      this.isCollapse = !this.isCollapse;
    },

    // 菜单生成(授权菜单数据)
    getMenus (list) {
      let _this = this;
      // 当前用户授权目录
      let treelis = JSON.parse(sessionStorage.getItem('allMenus'));

      // 循环匹配授权菜单的父级菜单
      for (let i = list.length; i--;) {
        // 循环所有菜单数据
        treelis.forEach(item => {
          // 匹配父级菜单目录ID
          if (list[i].parentId === item.id) {
            list.push(item);
          }
        });
      }

      let result = [];
      let obj = {};

      // 检测去重，避免授权菜单数据 与 匹配菜单数据重复
      for (let i = list.length; i--;) {
        if (!obj[list[i].id]) {
          result.push(list[i]);
          obj[list[i].id] = true;
        }
      }

      // 显示登录用户授权菜单
      _this.showTrees(result);
    },

    // 显示授权菜单(匹配过滤后的授权菜单数据)
    showTrees (data) {
      let lv1 = [];
      let lv2 = [];
      let lv3 = [];

      // 显示菜单数据模型转换
      for (let i = data.length; i--;) {
        if (data[i].parentId === 0) {
          lv1.push({
            index: data[i].id,
            icon: data[i].icon,
            title: data[i].menuName,
            sort: data[i].sort,
            submenus: []
          });
        } else if (data[i].parentId !== 74 && data[i].parentId !== 0) {
          lv2.push({
            index: data[i].id,
            parentId: data[i].parentId,
            path: data[i].router,
            subtitle: data[i].menuName,
            sort: data[i].sort,
            submenus: []
          });
        } else {
          lv3.push({
            index: data[i].id,
            parentId: data[i].parentId,
            path: data[i].router,
            subtitle: data[i].menuName,
            sort: data[i].sort
          });
        }
      }

      // 三级菜单关联二级菜单
      for (let i = lv2.length; i--;) {
        lv3.forEach(val3 => {
          if (lv2[i].index === val3.parentId) {
            lv2[i].submenus.push({
              index: val3.index,
              path: val3.path,
              subtitle: val3.subtitle,
              sort: val3.sort
            });
          }
        });
      }

      // 二级菜单关联一级菜单
      for (let i = lv1.length; i--;) {
        lv2.forEach(val2 => {
          if (lv1[i].index === val2.parentId) {
            lv1[i].submenus.push({
              index: val2.index,
              path: val2.path,
              subtitle: val2.subtitle,
              sort: val2.sort,
              submenus: val2.submenus
            });
          }
        });
      }
      // 菜单数据赋值
      this.menus = lv1;
    },

    // 获取该路由下授权按钮(菜单ID)
    getRole (index) {
      let _this = this;
      // 收集请求数据
      let params = {
        menuId: index,
        userId: _this.$store.state.userinfo.userId
      };
      // 根据ID请求该路由下 - 用户按钮级权限
      _this.$http.post('/api/findBtnByMenuIdAndUserId', params).then(res => {
        let { code, datas } = res;
        // 判断Code状态是否正确
        if (code === 0) {
          // 将授权按钮数据存入Vuex localstorage
          _this.$store.commit('setBtns', datas[0]);
          _this.btnlist = datas[0];
          // 子父组件通信 授权按钮数据传递给父组件
          _this.$emit('btns', this.btnlist);
        }
      }).catch(err => {
        if (err === undefined) {
          _this.$message({
            message: '服务器响应异常！',
            type: 'error'
          });
          return false;
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
@import './index.scss';
</style>
